/*

 罗亮富 2018.02
 */

#import <Foundation/Foundation.h>

#import "LAGOverLapImageScrollView.h"
#import "OverLapImageLay.h"
#import <UIKitUtli/UIKitUtli.h>


#pragma mark -

@interface LAGOverLapImageScrollView () <UIScrollViewDelegate>
{
    CGSize _imageSize;
    UIView *_actualZoomView;
    __weak MKMapView *_syncMovingMapView;
    
    OverLapImageLay *_testLayer;
   
    CLLocationCoordinate2D _orgCord;
    CLLocationCoordinate2D _rightBottomCord;
}

@end

@implementation LAGOverLapImageScrollView
@synthesize controlPannel = _controlPannel;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.zoomImageView = [[UIImageView alloc]initWithFrame:CGRectZero];
        self.showsVerticalScrollIndicator = YES;
        self.showsHorizontalScrollIndicator = YES;
        self.bouncesZoom = YES;
        self.zoomState = YES;
        self.contentAlpha = 0.5;
        self.decelerationRate = UIScrollViewDecelerationRateFast;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.delegate = self;
        UITapGestureRecognizer *doubleTpa = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAutoZoom:)];
        doubleTpa.numberOfTapsRequired = 2;
        [self addGestureRecognizer:doubleTpa];

    }
    return self;
}

- (void)layoutSubviews 
{
    [super layoutSubviews];
    
}

-(void)setContentAlpha:(CGFloat)a
{
    _contentAlpha = a;
    _testLayer.renderer.alpha = a;
    self.zoomImageView.alpha = a;
}

-(void)setHeightStrech:(CGFloat)heightStrech
{
    CGAffineTransform t = self.zoomImageView.transform;
    self.zoomImageView.transform = CGAffineTransformIdentity;
    CGFloat k = (_imageSize.height/_imageSize.width);
    CGFloat h = heightStrech*k*self.zoomImageView.width;
    CGPoint c = self.zoomImageView.center;
    self.zoomImageView.frame = CGRectMake(self.zoomImageView.x, self.zoomImageView.y, self.zoomImageView.width, h);
    self.zoomImageView.center = c;
    self.zoomImageView.transform = t;
}

-(CGFloat)heightStrech
{
    if(!self.zoomImageView.image)
        return 1.0;
    
    CGFloat s = (self.zoomImageView.height/self.zoomImageView.width)/(_imageSize.height/_imageSize.width);
    return s;
}

-(void)setImageRotation:(CGFloat)imageRotation
{
    self.zoomImageView.transform = CGAffineTransformRotate(CGAffineTransformIdentity, imageRotation);
}

-(CGFloat)imageRotation
{
    CGAffineTransform t = self.zoomImageView.transform;
    return atan2(t.b, t.a);
}

-(void)setControlPannel:(LAGOperControlPannelView *)controlPannel
{
    _controlPannel = controlPannel;
    __weak typeof(self) weak_self = self;
    controlPannel.alpaChangeHandleBlock = ^(float a)
    {
        [weak_self setContentAlpha:a];
    };
    
    controlPannel.imageiInterActiveChangedBlock = ^(LAGreactImageMapMode mode)
    {
        if(mode == LAGreactImageMapSync)
        {
            [weak_self startSynchronizeMovingViewMapView:self.overlappedMapView];
        }
        else
        {
            [weak_self releaseSynchronizeMoving];
            weak_self.userInteractionEnabled = (mode==LAGreactImageMode);
        }
    };
    
    controlPannel.imageHeightStrechHandleBlock = ^(float hStrech) {
        weak_self.heightStrech = hStrech;
    };
    
    controlPannel.imageRotateHandleBlock = ^(double rotation)
    {
        weak_self.imageRotation = rotation;
    };
    
}

#pragma mark- GestureRecogonizer


-(void)tapAutoZoom:(UITapGestureRecognizer *)rgz
{

}



-(UIView *)viewToZoom
{
    return self.zoomImageView;
}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    if ( self.zoomState ) {
        return _actualZoomView;
    }
    return nil;
}



- (void)displayImage:(UIImage *)image
{
    _imageSize = image.size;
    if(!_actualZoomView)
    {
        _actualZoomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _imageSize.width*1000000, _imageSize.height*1000000)];
      //  _actualZoomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _imageSize.width+self.width*2, _imageSize.height+self.height*2)];
        [self addSubview:_actualZoomView];
        [_actualZoomView addSubview:self.zoomImageView];
        _actualZoomView.backgroundColor = [UIColor clearColor];
    }

    [self.zoomImageView setImage:image];
    
    self.zoomScale = 1.0;

    CGSize ctSize = _actualZoomView.frame.size;
    self.contentSize = ctSize;
    self.contentOffset = CGPointMake(self.contentSize.width/2-self.frame.size.width/2, self.contentSize.height/2-self.frame.size.height/2);//居中
    self.zoomImageView.frame = CGRectMake((self.contentSize.width-_imageSize.width)/2, (self.contentSize.height-_imageSize.height)/2, _imageSize.width, _imageSize.height);
    
    self.maximumZoomScale = 99999999;
    self.minimumZoomScale = MIN(1,(self.frame.size.width/_imageSize.width)*0.00001);
    
}

#pragma mark-

-(UIImage *)imageImageToOverLap
{
    UIImage *retImage = self.zoomImageView.image;
    CGAffineTransform t = self.zoomImageView.transform;
    if(!CGAffineTransformIsIdentity(t))
    {
        retImage = [retImage imageRotatedByRadians:atan2(t.b, t.a)];// [self rotatedImage:retImage degree:atan2(t.b, t.a)];
    }
    return retImage;
}


-(void)startSynchronizeMovingViewMapView:(MKMapView *)mapView
{
    self.userInteractionEnabled = NO;
    self.hidden = YES;

    _syncMovingMapView = mapView;
    _syncMovingMapView.rotateEnabled = NO;
    CGRect imageRect = self.zoomImageView.frame;

    _orgCord = [_syncMovingMapView convertPoint:imageRect.origin toCoordinateFromView:self.zoomImageView.superview];
    _rightBottomCord = [_syncMovingMapView
                                              convertPoint:CGPointMake(imageRect.origin.x+imageRect.size.width, imageRect.origin.y+imageRect.size.height)
                                              toCoordinateFromView:self.zoomImageView.superview];
    MKMapPoint mkOrg = MKMapPointForCoordinate(_orgCord);
    MKMapPoint mkrightBottom = MKMapPointForCoordinate(_rightBottomCord);
    MKMapRect imageOccupiedMapRect = MKMapRectMake(mkOrg.x, mkOrg.y, mkrightBottom.x-mkOrg.x, mkrightBottom.y-mkOrg.y);
   
    
    if(_testLayer)
        [_syncMovingMapView removeOverlay:_testLayer];
    _testLayer = [[OverLapImageLay alloc]initWithImage:[self imageImageToOverLap] onMapRect:imageOccupiedMapRect alpha:self.contentAlpha];
    [_syncMovingMapView addOverlay:_testLayer];
    
}


-(void)releaseSynchronizeMoving
{
    if(!_syncMovingMapView)
        return;
    
    self.userInteractionEnabled = YES;
    self.hidden = NO;
    
    _syncMovingMapView.rotateEnabled = NO;
    
    //通过平移/缩放 将图片与mapview上的layer图片内容重叠
    CGPoint p1 = [_syncMovingMapView convertCoordinate:_orgCord toPointToView:self.zoomImageView.superview];
    CGPoint p2 = [_syncMovingMapView convertCoordinate:_rightBottomCord toPointToView:self.zoomImageView.superview];

    CGFloat k = fabs(p2.x-p1.x)/self.zoomImageView.width;

    CGFloat newScale = self.zoomScale*k;
    self.zoomScale = newScale;
    
    CGPoint p0 = [_syncMovingMapView convertCoordinate:_orgCord toPointToView:self.zoomImageView.superview];
    CGPoint offset = CGPointMake(self.contentOffset.x-(p0.x-self.zoomImageView.x)*newScale, self.contentOffset.y-(p0.y-self.zoomImageView.y)*newScale);
    self.contentOffset = offset;

    if(_testLayer)
        [_syncMovingMapView removeOverlay:_testLayer];
    
    _syncMovingMapView = nil;
}

//下面这些方法虽然没有用到，但都是一些很好的处理逻辑，可以借鉴
//-(void)syncMovemoentForMapView:(MKMapView *)mapView
//{
//    id mapGestureController = [mapView valueForKey:@"gestureController"];
//    [self.panGestureRecognizer addTarget:mapGestureController action:@selector(handlePan:)];
//    [self.pinchGestureRecognizer addTarget:mapGestureController action:@selector(handlePinch:)];
//}
//
//-(void)unsyncMoveMentForMapView:(MKMapView *)mapView
//{
//    NSMutableArray *panTargets = [self.panGestureRecognizer valueForKey:@"_targets"];
//    NSMutableArray *pinchTargets = [self.pinchGestureRecognizer valueForKey:@"_targets"];
//    if(panTargets.count > 1)
//        [panTargets removeObjectAtIndex:1];
//    if(pinchTargets.count > 1)
//        [pinchTargets removeObjectAtIndex:1];
//}

//- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
//{
//
//    [self replaceWithZooming:scrollView withView:view atScale:scrollView.zoomScale];
//}
//
//-(void)replaceWithZooming:(UIScrollView *)scrollView withView:(UIView *)viewActuaZoom atScale:(CGFloat)scale
//{
//    UIView *view = viewActuaZoom;//self.zoomImageView;
//    CGPoint preOffset = scrollView.contentOffset;
//    CGSize ctSize = [self contentSizeForSubViewSize];
//    /*
//     1、view的原点相对于scrollView原点的偏移 poff1;
//     2、获取新的ctSize
//     3、view的中心至于新content的中心
//     4、计算view的原点对于scrollView原点的偏移 poff2;
//     4、新的offset即  poff2-poff1
//     */
//    CGPoint poff1 = CGPointMake(view.x-preOffset.x, view.y-preOffset.y);
//    self.contentSize = ctSize;
//    view.center = CGPointMake(ctSize.width/2, ctSize.height/2);
//    CGPoint poff2 = CGPointMake(view.x-preOffset.x, view.y-preOffset.y);
//    CGPoint newOffset = CGPointMake(preOffset.x+(poff2.x-poff1.x), preOffset.y+(poff2.y-poff1.y));
//    scrollView.contentOffset = newOffset;
//}
//
//-(CGSize)contentSizeForSubViewSize
//{
//    CGSize s = CGSizeMake(_imageSize.width*self.zoomScale, _imageSize.height*self.zoomScale);
//    return  CGSizeMake(s.width+(self.frame.size.width-10)*2, s.height+(self.frame.size.height-10)*2);
//}
 


@end
